﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Mime;
using System.Web;
using System.Web.Mvc;
using Sausage.Common;
using Sausage.Web.Code;
using Sausage.Web.Domain;
using Sausage.Web.Models;
using Sausage.Web.DataModel;

namespace Sausage.Web.Controllers
{
    /// <summary>
    /// 工程信息控制器
    /// </summary>
    /// <remarks></remarks>
    public class ProjectController : Controller
    {
        /// <summary>
        /// 默认动作。
        /// </summary>
        /// <returns></returns>
        /// <remarks></remarks>
        [ValidateInput(false)]
        [RequireAuthorization]
        [HandleError(Order = 3, ExceptionType = typeof(UnauthenticatedException), View = "Unauthenticated")]
        [HandleError(Order = 2, ExceptionType = typeof(UnauthorizedException), View = "Unauthorized")]
        [HandleError(Order = 1, ExceptionType = typeof(Exception), View = "Exception")]
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 默认动作。
        /// </summary>
        /// <returns></returns>
        /// <remarks></remarks>
        [RequireAuthorization]
        [HandleError(Order = 3, ExceptionType = typeof(UnauthenticatedException), View = "Unauthenticated")]
        [HandleError(Order = 2, ExceptionType = typeof(UnauthorizedException), View = "Unauthorized")]
        [HandleError(Order = 1, ExceptionType = typeof(Exception), View = "Exception")]
        public ActionResult Closed()
        {
            return View();
        }

        /// <summary>
        /// 默认动作。
        /// </summary>
        /// <returns></returns>
        /// <remarks></remarks>
        [ValidateInput(false)]
        [RequireAuthorization]
        [HandleError(Order = 3, ExceptionType = typeof(UnauthenticatedException), View = "Unauthenticated")]
        [HandleError(Order = 2, ExceptionType = typeof(UnauthorizedException), View = "Unauthorized")]
        [HandleError(Order = 1, ExceptionType = typeof(Exception), View = "Exception")]
        public ActionResult Submit()
        {
            return View();
        }

        /// <summary>
        /// 确认。
        /// </summary>
        /// <returns></returns>
        /// <remarks></remarks>
        [RequireAuthorization]
        [HandleError(Order = 3, ExceptionType = typeof(UnauthenticatedException), View = "Unauthenticated")]
        [HandleError(Order = 2, ExceptionType = typeof(UnauthorizedException), View = "Unauthorized")]
        [HandleError(Order = 1, ExceptionType = typeof(Exception), View = "Exception")]
        public ActionResult Confirm()
        {
            return View();
        }

        /// <summary>
        /// 默认动作。
        /// </summary>
        /// <returns></returns>
        /// <remarks></remarks>
        [HandleError(Order = 3, ExceptionType = typeof(UnauthenticatedException), View = "Unauthenticated")]
        [HandleError(Order = 2, ExceptionType = typeof(UnauthorizedException), View = "Unauthorized")]
        [HandleError(Order = 1, ExceptionType = typeof(Exception), View = "Exception")]
        public ActionResult ViewProject(Guid projectID)
        {
            var model = ProjectHelper.GetProjectByID(projectID);
            return View(model);
        }

        /// <summary>
        /// 返回参照数据。
        /// </summary>
        /// <param name="includeEmpty">是否包含空白项目。</param>
        /// <returns></returns>
        /// <remarks></remarks>
        [HttpGet]
        [JsonHandleError]
        [PermissionCheckAttribute("*")]
        public JsonResult Reference()
        {
            var data = ProjectHelper.GetProjectReference();

            //返回结果
            return Json(new JsonResultViewModel { data = data, total = data.Count, success = true },
                        JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 查询工程项目信息列表
        /// </summary>
        /// <param name="query">查询条件模型。</param>
        /// <returns>查询的工程项目信息列表</returns>
        /// <remarks></remarks>
        [HttpGet]
        [JsonHandleError]
        [PermissionCheckAttribute("ProjectCreater")]
        public JsonResult SubmitSelect(JosnPagingQueryModel query)
        {
            var result = ProjectHelper.SubmitSelect(query);

            //返回结果
            return new JsonNetResult()
            {
                Data = new JsonResultViewModel
                {
                    success = true,
                    data = result.Data,
                    total = result.Total,
                    message = "工程信息加载成功！"
                },
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };
        }

        /// <summary>
        /// 查询工程项目信息列表
        /// </summary>
        /// <param name="query">查询条件模型。</param>
        /// <returns>查询的工程项目信息列表</returns>
        /// <remarks></remarks>
        [HttpGet]
        [JsonHandleError]
        [PermissionCheckAttribute("ProjectApprover")]
        public JsonResult ConfirmSelect(JosnPagingQueryModel query)
        {
            var result = ProjectHelper.ConfirmSelect(query);

            //返回结果
            return new JsonNetResult()
            {
                Data = new JsonResultViewModel
                {
                    success = true,
                    data = result.Data,
                    total = result.Total,
                    message = "工程信息加载成功！"
                },
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };
        }

        /// <summary>
        /// 查询工程项目信息列表
        /// </summary>
        /// <param name="query">查询条件模型。</param>
        /// <returns>查询的工程项目信息列表</returns>
        /// <remarks></remarks>
        [HttpGet]
        [JsonHandleError]
        [PermissionCheckAttribute("ProjectApprover")]
        public JsonResult ClosedSelect(JosnPagingQueryModel query)
        {
            var result = ProjectHelper.ClosedSelect(query);

            //返回结果
            return new JsonNetResult()
            {
                Data = new JsonResultViewModel
                {
                    success = true,
                    data = result.Data,
                    total = result.Total,
                    message = "工程信息加载成功！"
                },
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };
        }

        /// <summary>
        /// 查询工程项目信息列表
        /// </summary>
        /// <param name="query">查询条件模型。</param>
        /// <returns>查询的工程项目信息列表</returns>
        /// <remarks></remarks>
        [HttpGet]
        [JsonHandleError]
        [PermissionCheckAttribute("*")]
        public JsonResult ActiveSelect(JosnPagingQueryModel query)
        {
            var result = ProjectHelper.ActiveSelect(query);

            //返回结果
            return new JsonNetResult()
            {
                Data = new JsonResultViewModel
                {
                    success = true,
                    data = result.Data,
                    total = result.Total,
                    message = "工程信息加载成功！"
                },
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };
        }

        /// <summary>
        /// 查询工程项目信息列表
        /// </summary>
        /// <param name="query">查询条件模型。</param>
        /// <returns>查询的工程项目信息列表</returns>
        /// <remarks></remarks>
        [HttpGet]
        [JsonHandleError]
        [PermissionCheckAttribute("*")]
        public JsonResult Select(JosnPagingQueryModel query)
        {
            var result = ProjectHelper.Select(query);

            //返回结果
            return new JsonNetResult()
            {
                Data = new JsonResultViewModel
                            {
                                success = true,
                                data = result.Data,
                                total = result.Total,
                                message = "工程信息加载成功！"
                            },
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };
        }

        /// <summary>
        /// 删除工程信息
        /// </summary>
        /// <returns></returns>
        /// <remarks></remarks>
        [HttpPost]
        [JsonHandleError]
        [PermissionCheckAttribute("ProjectCreater")]
        public JsonResult Delete(ProjectListRow data)
        {
            ProjectHelper.DeleteProject(data.ProjectID);
            return Json(new JsonResultViewModel { success = true, message = "工程信息删除成功！" }, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 工程详细信息。
        /// </summary>
        /// <param name="id">工程项目编号。</param>
        /// <returns></returns>
        /// <remarks></remarks>
        [HttpPost]
        [JsonHandleError]
        [PermissionCheckAttribute("*")]
        public ActionResult Details(Guid id)
        {
            var project = ProjectHelper.GetProjectByID(id);
            if (project == null)
                return Json(new JsonResultViewModel { success = true, message = "找不到此工程信息！" },
                            JsonRequestBehavior.AllowGet);


            var data = new ProjectListRow()
                 {
                     ProjectID = project.ProjectID,
                     ProjectCode = project.ProjectCode,
                     ProjectName = project.ProjectName,
                     Organization = project.Organization.OrganizationName,
                     Category = project.ProjectCategory.ItemName,
                     CategoryID = project.CategoryID,
                     Roadway = project.Roadway,
                     BeginStake = project.BeginStake,
                     EndStake = project.EndStake,
                     GrantNumber = project.GrantNumber,
                     StartDate = project.StartDate,
                     CompletionDate = project.CompletionDate,
                     ProjectLeader = project.ProjectLeader,
                     TechnicalChief = project.TechnicalChief,
                     QualityChief = project.QualityChief,
                     Budget = project.Budget,
                     ApprovedBudget = project.ApprovedBudget,
                     CreateDate = project.CreateDate,
                     ApprovedDate = project.ApprovedDate,
                     CloseDate = project.CloseDate,
                     State = project.State
                 };

            //返回结果
            return new JsonNetResult()
                       {
                           Data = new JsonResultViewModel
                                      {
                                          success = true,
                                          total = 1,
                                          data = data,
                                          message = "工程信息加载成功！"
                                      },
                           JsonRequestBehavior = JsonRequestBehavior.AllowGet
                       };
        }

        /// <summary>
        /// 创建项目
        /// </summary>
        /// <returns>要创建的项目信息。</returns>
        /// <remarks></remarks>
        [HttpPost]
        [JsonHandleError]
        [PermissionCheckAttribute("ProjectCreater")]
        public JsonResult Create(ProjectListRow data)
        {
            if (ProjectHelper.GetProjectByName(data.ProjectName) != null)
                return Json(new JsonResultViewModel { success = false, message = "添加工程信息失败！已有同名项目，请更换项目名称！", data = Guid.NewGuid() }, JsonRequestBehavior.AllowGet);

            if (ProjectHelper.GetProjectByCode(data.ProjectCode) != null)
                return Json(new JsonResultViewModel { success = false, message = "添加工程信息失败！已有同标号项目，请更换项目编号！", data = Guid.NewGuid() }, JsonRequestBehavior.AllowGet);

            //创建工程
            Guid projectID = ProjectHelper.CreateProject(data);

            //返回结果
            return Json(new JsonResultViewModel { success = true, message = "添加工程信息成功！", data = projectID }, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 更新项目
        /// </summary>
        /// <returns>要更新的项目信息。</returns>
        /// <remarks></remarks>
        [HttpPost]
        [JsonHandleError]
        [PermissionCheckAttribute("ProjectCreater|ProjectApprover")]
        public JsonResult Update(ProjectListRow data)
        {
            ProjectHelper.UpdateProject(data);

            //返回结果
            return Json(new JsonResultViewModel { success = true, message = "更新工程信息成功！" }, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 删除附件
        /// </summary>
        /// <returns>操作结果。</returns>
        /// <remarks></remarks>
        [HttpPost]
        [JsonHandleError]
        [PermissionCheckAttribute("ProjectCreater|ProjectApprover")]
        public JsonResult DeleteAttachment(ProjectAttachmentModel data)
        {
            if (ProjectHelper.DeleteAttachment(data))
                return Json(new JsonResultViewModel { success = true, message = "删除项目附件成功！", data = Guid.NewGuid() },
                            JsonRequestBehavior.AllowGet);
            return Json(new JsonResultViewModel { success = false, message = "删除项目附件失败！", data = Guid.NewGuid() },
                        JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 查询附件信息
        /// </summary>
        /// <returns>查询结果。</returns>
        /// <remarks></remarks>
        [HttpGet]
        [JsonHandleError]
        [PermissionCheckAttribute("*")]
        public JsonResult Attachments(Guid projectID)
        {
            var result = ProjectHelper.GetProjectAttachment(projectID);

            //返回结果-
            return Json(new JsonResultViewModel
                            {
                                success = true,
                                total = result.Count,
                                message = "项目附件信息加载成功！",
                                data = result.Select(item => new ProjectAttachmentModel
                                                                 {
                                                                     AttachmentID = item.AttachmentID,
                                                                     AttachmentName = item.AttachmentName,
                                                                     FileExtension = item.FileExtension,
                                                                     ProjectID = item.ProjectID,
                                                                     IsOpen = item.IsOpen
                                                                 }).ToList()
                            }, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 下载附件
        /// </summary>
        /// <param name="attachmentID">附件编号。</param>
        [HttpGet]
        [JsonHandleError]
        [PermissionCheckAttribute("*")]
        public ActionResult DownloadAttachment(Guid attachmentID)
        {
            var attachment = ProjectHelper.GetAttachment(attachmentID);

            if (attachment == null)
                return Json(new JsonResultViewModel { success = false, message = "没有此项目附件！", data = Guid.NewGuid() }, JsonRequestBehavior.AllowGet);

            return
                File(
                    string.Concat(Server.MapPath(Utility.ProjectFolder), Path.DirectorySeparatorChar,
                                  attachment.AttachmentID, attachment.FileExtension),
                    Utility.GetContentTypeFromFileExtension(attachment.FileExtension),
                    attachment.AttachmentName);
        }

        /// <summary>
        /// 提交
        /// </summary>
        /// <param name="projectID">The project ID.</param>
        /// <returns>
        /// 执行结果
        /// </returns>
        [HttpPost]
        [JsonHandleError]
        [PermissionCheckAttribute("ProjectCreater")]
        public JsonResult ExecuteSubmit(Guid projectID)
        {
            ProjectHelper.ExecuteSubmit(projectID);
            //返回结果
            return Json(new JsonResultViewModel { success = true, message = "工程项目提交成功！" }, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 关闭
        /// </summary>
        /// <param name="projectID">The project ID.</param>
        /// <returns>
        /// 执行结果
        /// </returns>
        [HttpPost]
        [JsonHandleError]
        [PermissionCheckAttribute("ProjectApprover")]
        public JsonResult ExecuteClose(Guid projectID)
        {
            ProjectHelper.ExecuteClose(projectID);
            //返回结果
            return Json(new JsonResultViewModel { success = true, message = "工程项目提交成功！" }, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 批准
        /// </summary>
        /// <param name="labours">The labours.</param>
        /// <param name="auditor">The auditor.</param>
        /// <returns>
        /// 执行结果
        /// </returns>
        [HttpPost]
        [JsonHandleError]
        [PermissionCheckAttribute("ProjectApprover")]
        public JsonResult ExecuteConfirm(Guid[] projects, bool passed)
        {
            ProjectHelper.ExecuteConfirm(projects, passed);
            //返回结果
            return Json(new JsonResultViewModel { success = true, message = "工程项目审核成功！" }, JsonRequestBehavior.AllowGet);
        }
    }
}
